<template>
    <el-dialog :title="titleMap[mode]" v-model="visible" destroy-on-close @closed="close" :close-on-click-modal="false" :close-on-press-escape="mode != 'show' ? false : true" fullscreen>
        <el-form :model="form" :rules="rules" :disabled="mode=='show'" label-width="130" ref="dialogForm" style="height: calc(100vh - 100px);overflow-y: auto;">
            <el-row :gutter="1">
                <el-col :span="6">
                    <el-form-item label="退货日期" prop="return_date">
						<el-date-picker v-model="form.return_date" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%" @change="updateFields"/>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="类型" prop="input_type">
                        <el-select v-model="form.input_type" placeholder="请选择" clearable @change="inputChange">
                            <el-option label="供应商" :value="1"></el-option>
                            <el-option label="染色厂" :value="2"></el-option>
                            <el-option label="加工厂" :value="3"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="退货单号" prop="return_code">
                        <el-input v-model="form.return_code" placeholder="退货单号" clearable @blur="updateFields"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-col :xs="24" :sm="12">
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" placeholder="备注" clearable @blur="updateFields"></el-input>
                </el-form-item>
            </el-col>
            <div class="flex">
                <div>
                    <span>新增</span>
                    <el-input v-model="bar_code" ref="barCodeInput" placeholder="放入条码" @keyup.enter="getTable($event)" @input="timeInput" :readonly="!form.input_type"></el-input>
                </div>
                <div>
                    <span>删除</span>
                    <el-input v-model="remove_bar_code" ref="removeBarCodeInput" placeholder="放入条码" @keyup.enter="removeCode" @input="timeInput"></el-input>
                </div>
            </div>

            <sc-form-table ref="table" class="formtable" v-model="form.detail" hideAdd hideDelete showIndex placeholder="暂无数据">
                <el-table-column label="序号" align="center" prop="index" width="50"></el-table-column>
                <el-table-column label="布卷条码" align="center" prop="roll_code"></el-table-column>
                <el-table-column label="供货商名称" align="center" prop="apply_name"></el-table-column>
                <el-table-column label="品名" align="center" prop="goods_name">
                    <template #default="scope">
                        <div style="cursor: pointer;" @click="price(scope.row,'品名')">{{scope.row.goods_name}}</div>
                    </template>
                </el-table-column>
                <el-table-column label="货号" align="center" prop="goods_code"></el-table-column>
                <el-table-column label="花型" align="center" prop="flower"></el-table-column>
                <el-table-column label="颜色" align="center" prop="color"></el-table-column>
                <el-table-column label="Color" align="center" prop="colorName"></el-table-column>
                <el-table-column label="码数" align="center" prop="code_number"></el-table-column>
                <el-table-column label="米数" align="center" prop="meter"></el-table-column>
                <el-table-column label="折码" align="center" prop="folding"></el-table-column>
            </sc-form-table>
        </el-form>
        <el-footer style="text-align: right;position: fixed;bottom: 0;right: 0;left: 0;padding: 10px 20px;background: #fff;border-top: 1px solid #eee;">
			<el-button @click="visible = false">取 消</el-button>
			<el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit(0)">保存</el-button>
		</el-footer>
    </el-dialog>
    <select-goods v-if="dialog.goods" ref="goodsDialog" @success="goodsBack" @closed="dialog.goods = false" :query="{is_show: 1}"></select-goods>
    <select-house v-if="dialog.house" ref="houseDialog" @success="houseBack" @closed="dialog.house = false" :query="{goods_id: form.goods_id, status: 1, can_use: 1}"></select-house><!-- 入库单选择 -->
    <select-flower v-if="dialog.flower" ref="flowerDialog" @success="flowerBack" @closed="dialog.flower = false" :query="{goods_id: form.goods_id,}"></select-flower><!-- 花型选择 -->
    <select-sample v-if="dialog.sample" ref="sampleDialog" @success="sampleBack" @closed="dialog.sample = false" :query="{goods_id: form.goods_id,}"></select-sample><!-- 样本选择 -->
</template>

<script>
import selectGoods from '@/views/basic/goods/selectGoods.vue';
import SelectHouse from '../../selectHouse.vue';
import SelectFlower from '../../selectFlower.vue';
import SelectSample from '../../selectSample.vue';

import config from '@/config'
export default {
    emits: ['success', 'closed'],
    components: { selectGoods, SelectHouse, SelectFlower, SelectSample},
    data() {
        return {
            mode: "add",
            titleMap: {
                add: '新增调拨单',
                edit: '编辑调拨单',
                show: '查看调拨单',
            },
            visible: false,
            isSaveing: false,
            dialog: {
                goods: false,
            },
            form: {
                id: "",
                return_code: "",
                input_type: "",
                total_count: "",
                total_meters: "",
                remark: "",
                return_date: this.moment().format('YYYY-MM-DD'),
            },
            rules: {
                input_type: [ {required: true, message: '请选择类型'} ],
            },
            bar_code: "",
            remove_bar_code: "",
            MusicYes: new Audio(`${config.API_URL}//audio/ok.wav`),
            MusicNo: new Audio(`${config.API_URL}/audio/error.wav`),
            table_index: 0,
        }
    },
    created() {
        this.timeInput = this.common.debounce(this.timeInput, 5000);
        // this.getTable = this.common.debounce(this.getTable, 500);
        // this.removeCode = this.common.debounce(this.removeCode, 500);
	},
    mounted() {
    },
    methods: {
        timeInput(){
            this.setData({id: this.form.id})
        },
        close() {
            this.$emit('closed')
            this.submit()
        },
        //显示
        open(mode = 'add') {
            this.mode = mode;
            this.visible = true;
            return this
        },
        async submit() {
            if(!this.form.input_type) return
            if(this.mode == 'show') return
            // var res = [];
            // if (this.form.id) {
            //     res = await this.$API.business.return.edit.post(this.form);
            // } else {
            //     res = await this.$API.business.return.add.post(this.form);
            // }
            if (this.form.id) {
                this.$emit('success', this.form, this.mode)
            } else {
                var res = await this.$API.business.return.add.post(this.form);
                if (res.code == 1) {
                    this.$emit('success', this.form, this.mode)
                    this.form.id = this.form.id?this.form.id:res.data.id
                    if(this.form.id){
                        this.setData({id: this.form.id})
                    }
                }else {
                    this.$alert(res.message, "提示", {type: 'error'})
                    this.remove_bar_code = this.bar_code
                    this.removeCode()
                }
            }
        },
        //表单注入数据
        async setData(data) {
            this.form.id = data.id
            var res = await this.$API.business.return.detail.get({id: data.id});
            this.form.return_code = res.data.return_code
            this.form.return_date = res.data.return_date
            this.form.input_type = res.data.input_type
            this.table_index = res.data.detail.length
            let array = []
            res.data.detail.map(item=>{
                array.push({
                    id: item.id,
                    index: item.index,
                    goods_id: item.goods_id,
                    inspect_id: item.inspect_id,
                    roll_code: item.inspect?.roll_code,
                    apply_name: item.inspect?.apply_name,
                    goods_code: item.inspect?.goods_code,
                    goods_name: item.inspect?.goods_name,
                    number: item.inspect?.number,
                    code_number: item.inspect?.code_number,
                    meter: item.inspect?.meter,
                    folding: item.inspect?.folding?.name,
                    color: item.inspect?.color,
                    colorName: item.inspect?.colorName?.name,
                    flower: item.inspect?.flower,
                    sales_price: item.sales_price,
                    total_price: item.total_price,
                    zd_price: item.zd_price,
                    shipping_cost: item.shipping_cost,

                })
            })
            this.form.detail = array
        },

        async getTable(){
            if(!this.bar_code) return
            var res = await this.$API.business.return.scan.get({roll_code: this.bar_code,action_type: 1,return_id: this.form.id})
            if(res.code == 1){
                this.MusicYes.play()
                const maxIndex = this.form.detail.length > 0 ? Math.max(...this.form.detail.map(item => item.index)) : 0
                const newIndex = maxIndex + 1
                let array = []
                let form = {
                    index: newIndex,
                    inspect_id: res.data.id,
                    roll_code: res.data.roll_code,
                    apply_name: res.data.apply_name,
                    goods_id: res.data.goods_id,
                    goods_code: res.data.goods_code,
                    goods_name: res.data.goods_name,
                    number: res.data.number,
                    folding: res.data.folding?.name,
                    code_number: res.data.code_number,
                    meter: res.data.meter,
                    color: res.data.color,
                    colorName: res.data.colorName?.name,
                    flower: res.data.flower,
                }
                array.push(form)
			    this.form.detail = [...this.form.detail, ...array]
                this.total()
                this.form.total_count = this.form.detail.length
                this.bar_code = ""
                // setTimeout(()=>{
                //     this.submit()
                // },10)
            }else{
                this.MusicNo.play()
                this.$message.error(res.message)
                this.$refs.barCodeInput.select()
            }
        },
        async removeCode(){
            if(!this.remove_bar_code) return
            var res = await this.$API.business.return.scan.get({roll_code: this.remove_bar_code,action_type: 2,return_id: this.form.id})
            if(res.code == 1){
                this.MusicYes.play()
                this.table_index - 1
                const index = this.form.detail.findIndex(item => item.roll_code == this.remove_bar_code)
                if(index !== -1){
                    this.$message.success("删除成功!")
                    this.form.detail.splice(index, 1)
                    if (this.form.detail && this.form.detail.length > 0) {
                        const sortedItems = [...this.form.detail].sort((a, b) => a.index - b.index);
                        this.form.detail.forEach((item, idx) => {
                            const sortedIndex = sortedItems.findIndex(sortedItem => sortedItem.roll_code === item.roll_code);
                            item.index = sortedIndex !== -1 ? sortedIndex + 1 : idx + 1;
                        });
                        this.table_index = Math.max(...this.form.detail.map(item => item.index));
                    } else {
                        this.table_index = 0;
                    }
                    // this.submit()
                }else {
                    this.$message.error("此条数据不存在!")
                }
                this.remove_bar_code = ""
                this.bar_code = ""
            }else {
                this.MusicNo.play()
                this.$message.error(res.message)
                this.$refs.removeBarCodeInput.select()
            }
            this.total()
            this.form.total_count = this.form.detail.length
        },
        inputChange(){
            this.$nextTick(()=>{
                this.$refs.barCodeInput.focus()
            })
            this.submit()
        },
        total(){
            let total_code_number = 0
            this.form.detail.map(item=>{
                total_code_number = Number(item.code_number) + total_code_number
            })
            this.form.total_meters = (total_code_number).toFixed(2)
        },

        async updateFields(){
            if(!this.form.input_type) return
            if(this.mode == 'show') return
            let form = {
                id: this.form.id,
                return_date: this.form.return_date,
                return_code: this.form.return_code,
                remark: this.form.remark,
            }
            await this.$API.business.return.updateFields.post(form);
        },
    }
}
</script>

<style lang="scss" scoped>
.flex{
    display: flex;
    justify-content: space-between;
}
</style>
